package com.my.ext.utils;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.my.ext.entity.Admin;
import com.my.ext.mapper.AdminMapper;

import springfox.documentation.annotations.ApiIgnore;

public class AdminRealm extends AuthorizingRealm{

	@Autowired
	AdminMapper mapper;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Admin a = (Admin) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRole("admin");
		info.addStringPermission(a.getLevel() + "");
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upt = (UsernamePasswordToken)token;
		String username = upt.getUsername();
		String pwd = new String(upt.getPassword());
		Admin admin = mapper.login(username);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin, admin.getAuthcstring(), this.getName());
		return info;
	}

}
